package com.party.jackclientandroid.ui_home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ocnyang.pagetransformerhelp.cardtransformer.AlphaAndScalePageTransformer;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.adapter.MyPagerAdapter;
import com.party.jackclientandroid.adapter.VipPagerAdapter;
import com.party.jackclientandroid.api.CouponService;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.ImageBean;
import com.party.jackclientandroid.bean.SpellingGroupCouponDetail;
import com.party.jackclientandroid.controller.ConvertController;
import com.party.jackclientandroid.imageloader.GlideImageLoader;
import com.party.jackclientandroid.loadviewhelper.help.OnLoadViewListener;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.photoselector.PictureDetailActivity;
import com.party.jackclientandroid.ui_order.SubmitOrderActivity;
import com.party.jackclientandroid.utils.CommonUtil;
import com.party.jackclientandroid.utils.PhoneUtil;
import com.party.jackclientandroid.utils.TimeUtil;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;
import io.reactivex.functions.Consumer;

//拼团

public class SpellingGroupCouponDetailActivity extends BaseActivity {

    @BindView(R.id.whole_layout)
    RelativeLayout whole_layout;
    @BindView(R.id.remaining_time_cv)
    CountdownView remaining_time_cv;
    @BindView(R.id.remain_count_tv)
    TextView remain_count_tv;
    @BindView(R.id.coupon_name_tv)
    TextView coupon_name_tv;
    @BindView(R.id.contain_goods_ll)
    LinearLayout containGoodsLl;
    @BindView(R.id.buy_price_tv)
    TextView buy_price_tv;
    @BindView(R.id.original_buy_price_tv)
    TextView original_price_tv;
    @BindView(R.id.over_tv)
    TextView over_tv;
    @BindView(R.id.remain_time_ll)
    LinearLayout remain_time_ll;
    @BindView(R.id.no_goods_ll)
    LinearLayout no_goods_ll;
    @BindView(R.id.shop_name_tv)
    TextView shop_name_tv;
    @BindView(R.id.address_tv)
    TextView address_tv;

    @BindView(R.id.cardViewPager)
    ViewPager mViewPager;

    @BindView(R.id.rule_splicing)
    TextView rule_splicing;

    private long spellingGroupId;
    private CouponService couponService;
    private List<String> imagePathList = new ArrayList<>();
    private SpellingGroupCouponDetail spellingGroupCouponDetail;
    private MyPagerAdapter myPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spelling_group_coupon_detail);
        receivePassDataIfNeed(getIntent());
        initData();
    }

    protected void initData() {

        couponService = new CouponService(this);
        helper = new LoadViewHelper(whole_layout);
        helper.showLoading();
        helper.setListener(new OnLoadViewListener() {
            @Override
            public void onRetryClick() {
                helper.showLoading();
                getNeedData();
            }
        });
        getNeedData();
    }

    protected void receivePassDataIfNeed(Intent intent) {
        spellingGroupId = intent.getLongExtra("couponId", -1);
    }

    public void getNeedData() {
        addDisposableIoMain(couponService.getSpellingGroupCouponDetail(spellingGroupId), new DefaultConsumer<SpellingGroupCouponDetail>(mApplication) {

            @Override
            public void operateError(String message) {
                super.operateError(message);
                helper.showError();
            }

            @Override
            public void operateSuccess(BaseResult<SpellingGroupCouponDetail> result) {
                if (result.getData() != null) {
                    spellingGroupCouponDetail = result.getData();
                    setBanner();
                    setRemainingTime();
                    remain_count_tv.setText("库存：" + spellingGroupCouponDetail.getStockCount());
                    shop_name_tv.setText(spellingGroupCouponDetail.getShopName());
                    address_tv.setText(spellingGroupCouponDetail.getShopAddress());
                    coupon_name_tv.setText(spellingGroupCouponDetail.getShopName() + spellingGroupCouponDetail.getDinersNumberName());
                    buy_price_tv.setText("¥" + spellingGroupCouponDetail.getBuyPrice());
                    original_price_tv.setText("门市价:" + spellingGroupCouponDetail.getOriginalPrice());
                    rule_splicing.setText(Html.fromHtml(spellingGroupCouponDetail.getRuleSplicing()));
                    setCouponGoodsContent();
                    helper.showContent();
                } else {
                    helper.showEmpty();
                }
            }
        }, (Throwable throwable) -> {
            helper.showError();
        });
    }

    /**
     * 设置banner
     */
    public void setBanner() {
        imagePathList.add(spellingGroupCouponDetail.getGroupBuyImg());
        for (SpellingGroupCouponDetail.ItemsBean itemsBean : spellingGroupCouponDetail.getItems()) {
            imagePathList.add(itemsBean.getImgUrl());
        }

        myPagerAdapter = new MyPagerAdapter(imagePathList, (BaseActivity) mActivity);
        mViewPager.setAdapter(myPagerAdapter);
//        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setPageMargin(40);
        mViewPager.setPageTransformer(true, new AlphaAndScalePageTransformer());
        myPagerAdapter.setOnItemClickListener((View v) -> {
            int position = (int) v.getTag();
            ArrayList<ImageBean> urlList = new ArrayList<>();
            for (String imagePath : imagePathList) {
                ImageBean imageBean = new ImageBean();
                imageBean.setImgPath(imagePath);
                urlList.add(imageBean);
            }
            Intent intent = new Intent(mApplication, PictureDetailActivity.class);
            intent.putExtra("currentItem", position);
            intent.putExtra("dataList", urlList);
            intent.putExtra("deleteFlag", false);
            startActivity(intent);
        });
    }

    /**
     * 设置剩余时间（倒计时）
     */
    public void setRemainingTime() {
        long endSaleTime = spellingGroupCouponDetail.getEndSaleTime();
        long currSystemTime = TimeUtil.getCurrTimeStamp();
        long remainingTime = endSaleTime - currSystemTime;
        if (remainingTime > 0) {
            remain_time_ll.setVisibility(View.VISIBLE);
            over_tv.setVisibility(View.GONE);
            remaining_time_cv.start(remainingTime);
        } else {
            remain_time_ll.setVisibility(View.GONE);
            over_tv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置券的套餐详细内容
     */
    public void setCouponGoodsContent() {
        List<SpellingGroupCouponDetail.ItemsBean> itemsBeanList = spellingGroupCouponDetail.getItems();
        if (itemsBeanList.size() <= 0) {
            no_goods_ll.setVisibility(View.VISIBLE);
            containGoodsLl.setVisibility(View.GONE);
        } else {
            no_goods_ll.setVisibility(View.GONE);
            containGoodsLl.setVisibility(View.VISIBLE);
            for (SpellingGroupCouponDetail.ItemsBean itemsBean : itemsBeanList) {
                containGoodsLl.addView(getGoodsView(itemsBean));
            }
        }
    }

    public View getGoodsView(SpellingGroupCouponDetail.ItemsBean itemsBean) {
        View view = getLayoutInflater().inflate(R.layout.layout_contain_goods, null, false);
        ((TextView) view.findViewById(R.id.goods_name_tv)).setText(itemsBean.getTitle());
        ((TextView) view.findViewById(R.id.num_tv)).setText(itemsBean.getCount() + "份");
        ((TextView) view.findViewById(R.id.price_tv)).setText("¥" + itemsBean.getPrice());
        return view;
    }

    @OnClick({R.id.buy_btn, R.id.call_phone_iv})
    public void handleClickSth(View view) {
        switch (view.getId()) {
            case R.id.buy_btn:
                if (!isLogin()) {
                    handleToLogin();
                    return;
                }
                Intent intent = new Intent(mActivity, SubmitOrderActivity.class);
                intent.putExtra("goodDetail_data", ConvertController.getGoodsDetailObj(spellingGroupCouponDetail));
                startActivity(intent);
                break;
            case R.id.call_phone_iv:
                PhoneUtil.callPhone(mActivity, spellingGroupCouponDetail.getShopName(),
                        "电话号码：" + spellingGroupCouponDetail.getShopPhone(),
                        spellingGroupCouponDetail.getShopPhone());
                break;
        }
    }


}
